﻿using AutoMapper;
using B.Z.BasicData.API.Read.DTO;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using Common;
using MD5Hash;
using MediatR;

namespace B.Z.BasicData.API.Read.Application.User
{
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<LoginDto>>
    {
        private readonly IBaseRepository<T_User> userRepository;
        private readonly IBaseRepository<T_UserRole> urRepository;
        private readonly IBaseRepository<T_Role> roleRepository;
        private readonly IMapper mapper;
        private readonly JwtTools jwtTools;
        private readonly IConfiguration configuration;

        public LoginQueryCommandHandler(IBaseRepository<T_User> userRepository, IBaseRepository<T_UserRole> urRepository, IBaseRepository<T_Role> roleRepository, IMapper mapper, JwtTools jwtTools, IConfiguration configuration)
        {
            this.userRepository = userRepository;
            this.urRepository = urRepository;
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.jwtTools = jwtTools;
            this.configuration = configuration;
        }

        public Task<APIResult<LoginDto>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<LoginDto> result = new APIResult<LoginDto>();
            result.Code = APIEnum.ok;
            result.Message = "登陆成功";
            var user = userRepository.GetAll().FirstOrDefault(p=> p.UserName == request.UserName);
            if (user == null)
            {
                result.Code = APIEnum.faile;
                result.Message = "用户名不存在";
                return Task.FromResult(result);
            }
            if (user.Password != request.Password.GetMD5())
            {
                result.Code = APIEnum.faile;
                result.Message = "密码错误";
                return Task.FromResult(result);
            }
            var dto= mapper.Map<LoginDto>(user);
            dto.RidList= urRepository.GetAll().Where(x => x.Uid == user.Id).Select(p=>p.Rid).ToList();
            dto.RoleName=string.Join("、", roleRepository.GetAll().Where(x => dto.RidList.Contains(x.Id)).Select(x => x.RoleName));
            result.Token = jwtTools.JwtNewString(configuration, user);
            result.Data = dto;
            return Task.FromResult(result);
        }
    }
}
